package com.ssc.demo1;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Sender {
    //发送次数
    private static final int SEND_NUM=5;
    //tcp地址
    private static final String BROKER_url="tcp://49.234.233.179:61616";
    public static final String DESTINATION = "test1.mq.queue";

    public static void main(String[] args) throws Exception {
        Session session=null;
        ConnectionFactory connectionFactory=null;
        Connection connection=null;
        try {
            //第一步建立connectionFactory连接工厂，需要填入用户名，密码，以及要连接的地址
         connectionFactory=new ActiveMQConnectionFactory("ssc","ssc",BROKER_url );
       //第二步根据connectionFactory工厂对象给我们创建一个Connection连接，并且调用Connection的start方法开启连接
        connection=connectionFactory.createConnection();
        connection.start();
        //第三步通过Connection对象创建session会话（上下文环境对象），
        session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
        //创建一个消息队列
        Destination destination=session.createQueue(DESTINATION);
        //创建消息制作者
        MessageProducer messageProducer=session.createProducer(destination);
        //创建持久化模式
        messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sendMessage(session,messageProducer);
        session.commit();

        }catch (Exception e){
            throw e;
        }finally {
            //关闭释放资源
            if (session!=null){
                session.close();
            }
            if(connection!=null){
                connection.close();
            }
        }
    }
    public static void sendMessage(Session session,MessageProducer messageProducer)throws Exception{
        for (int i=0;i<SEND_NUM;i++){
            String message="发送消息第"+(i+1)+"条";
            TextMessage text=session.createTextMessage(message);
            System.out.println(message);
            messageProducer.send(text);
        }
    }
}
